<!DOCTYPE html><html lang="en" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0"><title>JUC学习日记1 | Unknown Blog</title><meta name="author" content="Ris Pika"><meta name="copyright" content="Ris Pika"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="❤该文档主要讲述包括以下内容❤ JMM Volatile 指令重拍 CAS ABA问题 可重入锁 自旋锁 死锁   1. JMM 面试题: 请你谈谈Volatile的理解?  -&gt; Volatile是Java 虚拟机提供轻量级的同步机制  保证可见性 不保证原子性 禁止指令重排   问题: 什么是JMM?  -&gt; JMM是java的内存模型 实际不存在,概念 关于JMM的一些同步的约定">
<meta property="og:type" content="article">
<meta property="og:title" content="JUC学习日记1">
<meta property="og:url" content="https://unkonwn.online/2023/03/01/JUC%E5%AD%A6%E4%B9%A0%E6%97%A5%E8%AE%B01/index.html">
<meta property="og:site_name" content="Unknown Blog">
<meta property="og:description" content="❤该文档主要讲述包括以下内容❤ JMM Volatile 指令重拍 CAS ABA问题 可重入锁 自旋锁 死锁   1. JMM 面试题: 请你谈谈Volatile的理解?  -&gt; Volatile是Java 虚拟机提供轻量级的同步机制  保证可见性 不保证原子性 禁止指令重排   问题: 什么是JMM?  -&gt; JMM是java的内存模型 实际不存在,概念 关于JMM的一些同步的约定">
<meta property="og:locale" content="en_US">
<meta property="og:image" content="https://pic.unkonwn.online//wallhaven-6dl2yw.jpg?imageView/1/w/500/h/500">
<meta property="article:published_time" content="2023-03-01T12:52:40.000Z">
<meta property="article:modified_time" content="2023-03-01T12:55:19.731Z">
<meta property="article:author" content="Ris Pika">
<meta property="article:tag" content="java">
<meta property="article:tag" content="JUC">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://pic.unkonwn.online//wallhaven-6dl2yw.jpg?imageView/1/w/500/h/500"><link rel="shortcut icon" href="/img/favicon.png"><link rel="canonical" href="https://unkonwn.online/2023/03/01/JUC%E5%AD%A6%E4%B9%A0%E6%97%A5%E8%AE%B01/index.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://lf6-cdn-tos.bytecdntp.com/cdn/expire-1-M/font-awesome/6.0.0/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-M/node-snackbar/0.1.16/snackbar.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","languages":{"hits_empty":"We didn't find any results for the search: ${query}"}},
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: 'Copy successfully',
    error: 'Copy error',
    noSupport: 'The browser does not support'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: 'Just',
    min: 'minutes ago',
    hour: 'hours ago',
    day: 'days ago',
    month: 'months ago'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: {"chs_to_cht":"Traditional Chinese Activated Manually","cht_to_chs":"Simplified Chinese Activated Manually","day_to_night":"Dark Mode Activated Manually","night_to_day":"Light Mode Activated Manually","bgLight":"#49b1f5","bgDark":"#121212","position":"top-right"},
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: false,
  }
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'JUC学习日记1',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2023-03-01 20:55:19'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
    win.getCSS = (url,id = false) => new Promise((resolve, reject) => {
      const link = document.createElement('link')
      link.rel = 'stylesheet'
      link.href = url
      if (id) link.id = id
      link.onerror = reject
      link.onload = link.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        link.onload = link.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(link)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 5.4.2"></head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">Loading...</div></div></div><script>const preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',()=> { preloader.endLoading() })

if (false) {
  document.addEventListener('pjax:send', () => { preloader.initLoading() })
  document.addEventListener('pjax:complete', () => { preloader.endLoading() })
}</script><div id="web_bg"></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src= "" data-lazy-src="http://pic.unkonwn.online//20140802211120_t34dW.jpeg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">Articles</div><div class="length-num">6</div></a><a href="/tags/"><div class="headline">Tags</div><div class="length-num">13</div></a><a href="/categories/"><div class="headline">Categories</div><div class="length-num">0</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fa fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fa fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fa fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/messageboard/"><i class="fa-fw fa fa-paper-plane"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fa fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/upadte/"><i class="fa-fw fa fa-bell"></i><span> 日志</span></a></div><div class="menus_item"><a class="site-page" href="/myself/"><i class="fa-fw fa fa-id-card"></i><span> Myself</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fa fa-list"></i><span> 菜单</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/%E5%85%B3%E4%BA%8E"><i class="fa-fw /about/"></i><span> 0</span></a></li><li><a class="site-page child" href="/butterfly%E4%B8%BB%E9%A2%98"><i class="fa-fw https://github.com/jerryc127/hexo-theme-butterfly/"></i><span> 1</span></a></li></ul></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://pic.unkonwn.online//wallhaven-6dl2yw.jpg')"><nav id="nav"><span id="blog-info"><a href="/" title="Unknown Blog"><span class="site-name">Unknown Blog</span></a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search" href="javascript:void(0);"><i class="fas fa-search fa-fw"></i><span> Search</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fa fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fa fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fa fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fa fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/messageboard/"><i class="fa-fw fa fa-paper-plane"></i><span> 留言板</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fa fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/upadte/"><i class="fa-fw fa fa-bell"></i><span> 日志</span></a></div><div class="menus_item"><a class="site-page" href="/myself/"><i class="fa-fw fa fa-id-card"></i><span> Myself</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fa fa-list"></i><span> 菜单</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/%E5%85%B3%E4%BA%8E"><i class="fa-fw /about/"></i><span> 0</span></a></li><li><a class="site-page child" href="/butterfly%E4%B8%BB%E9%A2%98"><i class="fa-fw https://github.com/jerryc127/hexo-theme-butterfly/"></i><span> 1</span></a></li></ul></div></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">JUC学习日记1</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">Created</span><time class="post-meta-date-created" datetime="2023-03-01T12:52:40.000Z" title="Created 2023-03-01 20:52:40">2023-03-01</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">Updated</span><time class="post-meta-date-updated" datetime="2023-03-01T12:55:19.731Z" title="Updated 2023-03-01 20:55:19">2023-03-01</time></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="JUC学习日记1"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">Post View:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h2 id="❤该文档主要讲述包括以下内容❤"><a href="#❤该文档主要讲述包括以下内容❤" class="headerlink" title="❤该文档主要讲述包括以下内容❤"></a><strong>❤该文档主要讲述包括以下内容❤</strong></h2><ol>
<li><strong>JMM</strong></li>
<li><strong>Volatile</strong></li>
<li><strong>指令重拍</strong></li>
<li><strong>CAS</strong></li>
<li><strong>ABA问题</strong></li>
<li><strong>可重入锁</strong></li>
<li><strong>自旋锁</strong></li>
<li><strong>死锁</strong></li>
</ol>
<hr>
<h2 id="1-JMM"><a href="#1-JMM" class="headerlink" title="1. JMM"></a>1. JMM</h2><blockquote>
<p>面试题: 请你谈谈Volatile的理解?</p>
</blockquote>
<p>-&gt; Volatile是Java 虚拟机提供<strong>轻量级的同步机制</strong></p>
<ol>
<li>保证可见性</li>
<li>不保证原子性</li>
<li>禁止指令重排</li>
</ol>
<blockquote>
<p>问题: 什么是JMM?</p>
</blockquote>
<p>-&gt; JMM是java的内存模型 实际不存在,概念</p>
<h4 id="关于JMM的一些同步的约定"><a href="#关于JMM的一些同步的约定" class="headerlink" title="关于JMM的一些同步的约定"></a><em><strong>关于JMM的一些同步的约定</strong></em></h4><ol>
<li>线程解锁后,必须把共享变量刷回主存</li>
<li>线程加锁前,必须把主存最新值更新到工作内存中</li>
<li>必须保证加锁和解锁是同一把锁</li>
</ol>
<h4 id="gt-变量运算示例图"><a href="#gt-变量运算示例图" class="headerlink" title="-&gt; 变量运算示例图"></a><em><strong>-&gt; 变量运算示例图</strong></em></h4><p><img src= "" data-lazy-src="https://pic.unkonwn.online//20230301151517.png"></p>
<hr>
<h2 id="2-Volatile"><a href="#2-Volatile" class="headerlink" title="2. Volatile"></a>2. Volatile</h2><h3 id="gt-保证可见性"><a href="#gt-保证可见性" class="headerlink" title="-&gt; 保证可见性"></a>-&gt; 保证可见性</h3><h4 id="1-问题代码"><a href="#1-问题代码" class="headerlink" title="1.问题代码"></a>1.问题代码</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Demo1</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="type">int</span> <span class="variable">n</span> <span class="operator">=</span> <span class="number">0</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="keyword">new</span> <span class="title class_">Thread</span>(()-&gt;&#123;</span><br><span class="line">            <span class="keyword">while</span> (n == <span class="number">0</span>) &#123;</span><br><span class="line">                <span class="comment">// 死循环</span></span><br><span class="line">            &#125;</span><br><span class="line">        &#125;).start();</span><br><span class="line">        <span class="comment">// 修改变量n,但仍未退出死循环</span></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            TimeUnit.SECONDS.sleep(<span class="number">1</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">        n = <span class="number">1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>**-&gt; 出现的问题: **修改变量n,但仍未退出死循环</p>
<h4 id="2-问题解决"><a href="#2-问题解决" class="headerlink" title="2.问题解决"></a>2.问题解决</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Demo1</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 新增关键字volatile</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">volatile</span> <span class="keyword">static</span> <span class="type">int</span> <span class="variable">n</span> <span class="operator">=</span> <span class="number">0</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="keyword">new</span> <span class="title class_">Thread</span>(()-&gt;&#123;</span><br><span class="line">            <span class="keyword">while</span> (n == <span class="number">0</span>) &#123;</span><br><span class="line">                <span class="comment">// 死循环</span></span><br><span class="line">            &#125;</span><br><span class="line">        &#125;).start();</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            TimeUnit.SECONDS.sleep(<span class="number">1</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">        n = <span class="number">1</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>-&gt; 通过volatile关键字保证了变量n的可见性-&gt;使线程1可以获取到主线程修改的最新的变量状态</strong></p>
<h3 id="gt-不保证原子性"><a href="#gt-不保证原子性" class="headerlink" title="-&gt; 不保证原子性"></a>-&gt; 不保证原子性</h3><h4 id="gt-问题代码"><a href="#gt-问题代码" class="headerlink" title="-&gt; 问题代码"></a>-&gt; 问题代码</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Demo2</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">volatile</span> <span class="keyword">static</span> <span class="type">int</span> <span class="variable">n</span> <span class="operator">=</span> <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; <span class="number">50000</span>; i++) &#123;</span><br><span class="line">            <span class="keyword">new</span> <span class="title class_">Thread</span>(()-&gt;&#123;</span><br><span class="line">                add();</span><br><span class="line">            &#125;).start();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">while</span> (Thread.activeCount()&gt;<span class="number">2</span>)&#123;</span><br><span class="line">            Thread.<span class="keyword">yield</span>();</span><br><span class="line">        &#125;</span><br><span class="line">        System.out.println(Thread.currentThread().getName() + <span class="string">&quot;:&quot;</span> + n);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">add</span><span class="params">()</span> &#123;</span><br><span class="line">        n++;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * res=&gt;</span></span><br><span class="line"><span class="comment">     * main:49998</span></span><br><span class="line"><span class="comment">     */</span></span><br></pre></td></tr></table></figure>

<p><strong>由以上代码可知,volatile关键词不会保证变量的原子性</strong></p>
<blockquote>
<p>拓展:  什么是原子性?</p>
<p>-&gt; 在执行变量修改的过程中,其他线程无法干预</p>
<p>-&gt; 一般使用锁的方式保证数据的原子性</p>
</blockquote>
<h4 id="gt-解决方案"><a href="#gt-解决方案" class="headerlink" title="-&gt; 解决方案"></a>-&gt; 解决方案</h4><ol>
<li><p><strong>Synchronize关键词</strong></p>
</li>
<li><p><strong>Lock方法</strong></p>
</li>
<li><p><strong>原子类(<code>juc</code>下<code>atomic</code>包)</strong></p>
</li>
</ol>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Demo2</span> &#123;</span><br><span class="line"><span class="comment">//    private volatile static int n = 0;</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">volatile</span> <span class="keyword">static</span> <span class="type">AtomicInteger</span> <span class="variable">n</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">AtomicInteger</span>(<span class="number">0</span>);</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="keyword">for</span> (<span class="type">int</span> <span class="variable">i</span> <span class="operator">=</span> <span class="number">0</span>; i &lt; <span class="number">50000</span>; i++) &#123;</span><br><span class="line">            <span class="keyword">new</span> <span class="title class_">Thread</span>(()-&gt;&#123;</span><br><span class="line">                add();</span><br><span class="line">            &#125;).start();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">while</span> (Thread.activeCount()&gt;<span class="number">2</span>)&#123;</span><br><span class="line">            Thread.<span class="keyword">yield</span>();</span><br><span class="line">        &#125;</span><br><span class="line">        System.out.println(Thread.currentThread().getName() + <span class="string">&quot;:&quot;</span> + n);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">add</span><span class="params">()</span> &#123;</span><br><span class="line"><span class="comment">//        n++;</span></span><br><span class="line">        n.getAndIncrement(); <span class="comment">//-&gt;代替n++ 底层使用CAS的方式实现</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * res=&gt;</span></span><br><span class="line"><span class="comment">     * main:50000</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><em><strong>-&gt; 完美解决问题</strong></em></p>
<p>原子类的底层都直接与操作系统底层相关,效率高!</p>
<h3 id="gt-保证了指令不会重排"><a href="#gt-保证了指令不会重排" class="headerlink" title="-&gt; 保证了指令不会重排"></a>-&gt; 保证了指令不会重排</h3><blockquote>
<p>什么是指令重排?</p>
<p>-&gt; 编译器优化重排</p>
<p>-&gt; 指令并行也会重排</p>
<p>-&gt; 内存系统也会重排</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="type">int</span> <span class="variable">x</span> <span class="operator">=</span> <span class="number">1</span>; <span class="comment">// 1</span></span><br><span class="line"><span class="type">int</span> <span class="variable">y</span> <span class="operator">=</span> <span class="number">2</span>; <span class="comment">// 2</span></span><br><span class="line">x = x + <span class="number">1</span>; <span class="comment">// 3</span></span><br><span class="line">y = x * x; <span class="comment">// 4</span></span><br><span class="line"><span class="comment">//我们期望的顺序 1234 而实际可能为2134  1324</span></span><br><span class="line"><span class="comment">// 但不可能为4123 -&gt; 指令重排仍然保持系统的可执行性</span></span><br></pre></td></tr></table></figure>

<p><strong>=&gt;假设a,b为全局变量且默认值都为0</strong></p>
<table>
<thead>
<tr>
<th>线程A</th>
<th>线程B</th>
</tr>
</thead>
<tbody><tr>
<td>x = a</td>
<td>y = b</td>
</tr>
<tr>
<td>b = 1</td>
<td>a = 2</td>
</tr>
</tbody></table>
<p><strong>正常的结果: x = y = 0</strong></p>
<p><strong>=&gt;而因为指令重排的存在,可能为导致结果的不同,如下</strong></p>
<p><strong>线程A单独执行,和线程B单独执行顺序调换也不会有影响,而一起执行问题出现!</strong></p>
<table>
<thead>
<tr>
<th>线程A</th>
<th>线程B</th>
</tr>
</thead>
<tbody><tr>
<td>b = 1</td>
<td>a = 2</td>
</tr>
<tr>
<td>x = a</td>
<td>y = b</td>
</tr>
</tbody></table>
<p><strong>执行重排的结果: x = 2, y = 1</strong></p>
<h4 id="gt-而volatile可以避免指令重排"><a href="#gt-而volatile可以避免指令重排" class="headerlink" title="*** -&gt; 而volatile可以避免指令重排***"></a>*** -&gt; 而volatile可以避免指令重排***</h4><p>内存屏障,cpu指令,作用: </p>
<ol>
<li>保证特定操作的执行顺序</li>
<li>可以保证内存可见性</li>
</ol>
<h2 id="3-单例模式"><a href="#3-单例模式" class="headerlink" title="3. 单例模式"></a>3. 单例模式</h2><h4 id="1-饿汉1"><a href="#1-饿汉1" class="headerlink" title="1. 饿汉1"></a>1. 饿汉1</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 懒汉式单例</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Hungary</span> &#123;</span><br><span class="line">    <span class="comment">// 静态变量,一启动就加载</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">Hungary</span> <span class="variable">hungary</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">Hungary</span>();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> Hungary <span class="title function_">getInstance</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> hungary;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="2-饿汉2"><a href="#2-饿汉2" class="headerlink" title="2. 饿汉2"></a>2. 饿汉2</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 懒汉式单例</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Hungary</span> &#123;</span><br><span class="line">    <span class="comment">// 静态变量,一启动就加载</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> Hungary hungary;</span><br><span class="line">    <span class="keyword">static</span> &#123;</span><br><span class="line">        hungary = <span class="keyword">new</span> <span class="title class_">Hungary</span>();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> Hungary <span class="title function_">getInstance</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> hungary;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>以上懒汉式单例可能会浪费空间!</p>
</blockquote>
<h4 id="3-懒汉式-DCL"><a href="#3-懒汉式-DCL" class="headerlink" title="3. 懒汉式 DCL"></a>3. 懒汉式 DCL</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 懒汉式单例</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Lazy</span> &#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> Lazy lazy;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> Lazy <span class="title function_">getInstance</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (lazy == <span class="literal">null</span>) &#123;</span><br><span class="line">            <span class="keyword">synchronized</span> (Lazy.class) &#123;</span><br><span class="line">                <span class="keyword">if</span> (lazy == <span class="literal">null</span>) &#123;</span><br><span class="line">                    lazy = <span class="keyword">new</span> <span class="title class_">Lazy</span>(); <span class="comment">// 不是原子操作</span></span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> lazy;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>此情况在指令重排下可能会产生问题!</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"> lazy = <span class="keyword">new</span> <span class="title class_">Lazy</span>(); <span class="comment">// 不是原子操作</span></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 1. 分配内存空间</span></span><br><span class="line"><span class="comment"> * 2. 执行构造方法</span></span><br><span class="line"><span class="comment"> * 3. 把对象指向这一个空间</span></span><br><span class="line"><span class="comment"> * 指令重排可能执行 1 3 2,导致多线程情况下,执行完了12,但未构建方法时,新的线程进去判断lazy不是null返回了结果产生了错误</span></span><br><span class="line"><span class="comment"> */</span></span><br></pre></td></tr></table></figure>

<p><em><strong>-&gt; 所以需要加上volatile关键字</strong></em></p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 懒汉式单例</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">Lazy</span> &#123;</span><br><span class="line">	<span class="comment">// 添加volatile关键词</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">volatile</span> <span class="keyword">static</span> Lazy lazy;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> Lazy <span class="title function_">getInstance</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (lazy == <span class="literal">null</span>) &#123;</span><br><span class="line">            <span class="keyword">synchronized</span> (Lazy.class) &#123;</span><br><span class="line">                <span class="keyword">if</span> (lazy == <span class="literal">null</span>) &#123;</span><br><span class="line">                    lazy = <span class="keyword">new</span> <span class="title class_">Lazy</span>(); <span class="comment">// 不是原子操作</span></span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> lazy;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>***-&gt; 反射可以破幻这种单例模式**</li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> <span class="keyword">throws</span> Exception &#123;</span><br><span class="line">    <span class="type">Lazy</span> <span class="variable">lazy</span> <span class="operator">=</span> Lazy.getInstance();</span><br><span class="line">    Constructor&lt;Lazy&gt; constructor = Lazy.class.getDeclaredConstructor(<span class="literal">null</span>);</span><br><span class="line">    constructor.setAccessible(<span class="literal">true</span>);</span><br><span class="line">    <span class="type">Lazy</span> <span class="variable">lazy1</span> <span class="operator">=</span> constructor.newInstance();</span><br><span class="line">    System.out.println(lazy);</span><br><span class="line">    System.out.println(lazy1);</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * res=&gt;</span></span><br><span class="line"><span class="comment">     * designModel.single.Lazy@d716361</span></span><br><span class="line"><span class="comment">     * designModel.single.Lazy@6ff3c5b5</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="4-枚举"><a href="#4-枚举" class="headerlink" title="4. 枚举"></a>4. 枚举</h4><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">enum</span> <span class="title class_">EnumSingle</span> &#123;</span><br><span class="line"></span><br><span class="line">    INSTANCE;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> EnumSingle <span class="title function_">getInstance</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> INSTANCE;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="4-深入理解CAS"><a href="#4-深入理解CAS" class="headerlink" title="4. 深入理解CAS"></a>4. 深入理解CAS</h2><h4 id="1-什么是CAS"><a href="#1-什么是CAS" class="headerlink" title="1. 什么是CAS?"></a>1. 什么是CAS?</h4><blockquote>
<p>CAS -&gt; compareAndSet : 比较 与 交换</p>
<p>CAS -&gt; 是CPU的底层并发原语</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">CASDemo</span> &#123;</span><br><span class="line">    <span class="comment">//CAS 比较与交换</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="type">AtomicInteger</span> <span class="variable">atomicInteger</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">AtomicInteger</span>(<span class="number">10</span>);</span><br><span class="line">        System.out.println(<span class="string">&quot;第一次CAS: &quot;</span> + atomicInteger.compareAndSet(<span class="number">10</span>, <span class="number">20</span>));</span><br><span class="line">        System.out.println(atomicInteger);</span><br><span class="line">        System.out.println(<span class="string">&quot;第二次CAS: &quot;</span> + atomicInteger.compareAndSet(<span class="number">10</span>, <span class="number">30</span>));</span><br><span class="line">        System.out.println(atomicInteger);</span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * 第一次CAS: true</span></span><br><span class="line"><span class="comment">         * 20</span></span><br><span class="line"><span class="comment">         * 第二次CAS: false</span></span><br><span class="line"><span class="comment">         * 20</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>可见在第二次CAS操作时,比较不一样时,不会更改数值!!!!</p>
</blockquote>
<h4 id="2-什么是unsafe类"><a href="#2-什么是unsafe类" class="headerlink" title="2. 什么是unsafe类?"></a>2. 什么是unsafe类?</h4><blockquote>
<p>Java无法操作内存!</p>
<p>而Java通过native可以调用c++</p>
<p>c++ 可以操作内存</p>
<p>故 java可以通过这个类来操作内存</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">Unsafe</span> <span class="variable">unsafe</span> <span class="operator">=</span> Unsafe.getUnsafe();</span><br><span class="line"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="type">long</span> valueOffset;</span><br><span class="line"></span><br><span class="line"><span class="keyword">static</span> &#123;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        valueOffset = unsafe.objectFieldOffset</span><br><span class="line">            (AtomicInteger.class.getDeclaredField(<span class="string">&quot;value&quot;</span>));</span><br><span class="line">    &#125; <span class="keyword">catch</span> (Exception ex) &#123; <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">Error</span>(ex); &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>-&gt; 通过unsafe类来获取内存的偏移</strong></p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">final</span> <span class="type">boolean</span> <span class="title function_">compareAndSet</span><span class="params">(<span class="type">int</span> expect, <span class="type">int</span> update)</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> unsafe.compareAndSwapInt(<span class="built_in">this</span>, valueOffset, expect, update);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>-&gt; 深入分析<code>getAndIncrement</code></strong></p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">final</span> <span class="type">int</span> <span class="title function_">getAndIncrement</span><span class="params">()</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> unsafe.getAndAddInt(<span class="built_in">this</span>, valueOffset, <span class="number">1</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">final</span> <span class="type">int</span> <span class="title function_">getAndAddInt</span><span class="params">(Object var1, <span class="type">long</span> var2, <span class="type">int</span> var4)</span> &#123;</span><br><span class="line">    <span class="type">int</span> var5;</span><br><span class="line">    <span class="keyword">do</span> &#123;</span><br><span class="line">        var5 = <span class="built_in">this</span>.getIntVolatile(var1, var2); <span class="comment">// 根据内存获取值</span></span><br><span class="line">    &#125; <span class="keyword">while</span>(!<span class="built_in">this</span>.compareAndSwapInt(var1, var2, var5, var5 + var4));</span><br><span class="line">	<span class="comment">// 通过自旋 -&gt; 不断增加</span></span><br><span class="line">    <span class="keyword">return</span> var5;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="5-ABA问题"><a href="#5-ABA问题" class="headerlink" title="5. ABA问题"></a>5. ABA问题</h2><p><img src= "" data-lazy-src="https://pic.unkonwn.online//20230301164226.png"></p>
<p><strong>在修改时,其他线程具有同样的c值,造成了修改</strong></p>
<h2 id="6-原子引用"><a href="#6-原子引用" class="headerlink" title="6. 原子引用"></a>6. 原子引用</h2><h4 id="AtomicStampedReference类"><a href="#AtomicStampedReference类" class="headerlink" title="AtomicStampedReference类"></a><code>AtomicStampedReference</code>类</h4><blockquote>
<p>坑: 包装类 Integer 在-128~127之内进行缓存,可以使用==比较,而超出这个范围,则会调用valueOf,比较对象,请使用equals方法!</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">CASDemo2</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="comment">// 如果泛型是包装类,注意引用问题</span></span><br><span class="line">        AtomicStampedReference&lt;Integer&gt; stampedReference = <span class="keyword">new</span> <span class="title class_">AtomicStampedReference</span>&lt;&gt;(<span class="number">10</span>,<span class="number">1</span>);</span><br><span class="line">        <span class="comment">//InitialStamp -&gt; 就相当于乐观锁的 version</span></span><br><span class="line">        <span class="keyword">new</span> <span class="title class_">Thread</span>(()-&gt;&#123;</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                TimeUnit.SECONDS.sleep(<span class="number">1</span>);</span><br><span class="line">            &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">            &#125;</span><br><span class="line">            System.out.println(stampedReference.compareAndSet(<span class="number">10</span>, <span class="number">12</span>, stampedReference.getStamp(),</span><br><span class="line">                    stampedReference.getStamp() + <span class="number">1</span>));</span><br><span class="line">            System.out.println(<span class="string">&quot;a1 &quot;</span> + stampedReference.getStamp());</span><br><span class="line">            System.out.println(stampedReference.compareAndSet(<span class="number">12</span>, <span class="number">10</span>, stampedReference.getStamp(),</span><br><span class="line">                    stampedReference.getStamp() + <span class="number">1</span>));</span><br><span class="line">            System.out.println(<span class="string">&quot;a2 &quot;</span> + stampedReference.getStamp());</span><br><span class="line">        &#125;).start();</span><br><span class="line">        <span class="keyword">new</span> <span class="title class_">Thread</span>(()-&gt;&#123;</span><br><span class="line">            <span class="type">int</span> <span class="variable">stamp</span> <span class="operator">=</span> stampedReference.getStamp();</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                TimeUnit.SECONDS.sleep(<span class="number">2</span>);</span><br><span class="line">            &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">            &#125;</span><br><span class="line">            System.out.println(stampedReference.compareAndSet(<span class="number">10</span>, <span class="number">13</span>, stamp, stamp + <span class="number">1</span>));</span><br><span class="line">            System.out.println(<span class="string">&quot;b1 &quot;</span> + stampedReference.getStamp());</span><br><span class="line">        &#125;).start();</span><br><span class="line">        <span class="comment">/**</span></span><br><span class="line"><span class="comment">         * res -&gt;</span></span><br><span class="line"><span class="comment">         * true</span></span><br><span class="line"><span class="comment">         * a1 2</span></span><br><span class="line"><span class="comment">         * true</span></span><br><span class="line"><span class="comment">         * a2 3</span></span><br><span class="line"><span class="comment">         * false</span></span><br><span class="line"><span class="comment">         * b1 3</span></span><br><span class="line"><span class="comment">         */</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>-&gt; 原理与乐观锁相同!</strong></p>
<h2 id="7-锁"><a href="#7-锁" class="headerlink" title="7. 锁!"></a>7. 锁!</h2><h4 id="1-非公平锁和公平锁"><a href="#1-非公平锁和公平锁" class="headerlink" title="1. 非公平锁和公平锁"></a>1. 非公平锁和公平锁</h4><ol>
<li>公平锁: 公平,不可插队</li>
<li>非公平锁: 不公平,可插队(默认)</li>
</ol>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 创建 的 ReentrantLock实例。这等效于使用 ReentrantLock(false).</span></span><br><span class="line">   <span class="keyword">public</span> <span class="title function_">ReentrantLock</span><span class="params">()</span> &#123;</span><br><span class="line">       sync = <span class="keyword">new</span> <span class="title class_">NonfairSync</span>();</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">   <span class="comment">/**</span></span><br><span class="line"><span class="comment">    *创建具有给定公平性策略的 ReentrantLock 实例。</span></span><br><span class="line"><span class="comment">    *参数：</span></span><br><span class="line"><span class="comment">    *公平 – true 如果此锁应使用公平排序策略</span></span><br><span class="line"><span class="comment">   */</span></span><br><span class="line">   <span class="keyword">public</span> <span class="title function_">ReentrantLock</span><span class="params">(<span class="type">boolean</span> fair)</span> &#123;</span><br><span class="line">       sync = fair ? <span class="keyword">new</span> <span class="title class_">FairSync</span>() : <span class="keyword">new</span> <span class="title class_">NonfairSync</span>();</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>

<h4 id="2-可重入锁"><a href="#2-可重入锁" class="headerlink" title="2. 可重入锁"></a>2. 可重入锁</h4><blockquote>
<p>简单讲像套娃: 锁里有锁!看例子吧!</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 可重入锁 Synchronize</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">LockDemo1</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="keyword">new</span> <span class="title class_">Thread</span>(()-&gt;&#123;</span><br><span class="line">            Phone.call();</span><br><span class="line">        &#125;,<span class="string">&quot;a&quot;</span>).start();</span><br><span class="line">        <span class="keyword">new</span> <span class="title class_">Thread</span>(()-&gt;&#123;</span><br><span class="line">            Phone.call();</span><br><span class="line">        &#125;,<span class="string">&quot;b&quot;</span>).start();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Phone</span>&#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">synchronized</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">call</span><span class="params">()</span> &#123;</span><br><span class="line">        System.out.println(Thread.currentThread().getName()+<span class="string">&quot;:call&quot;</span>);</span><br><span class="line">        sms();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">synchronized</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">sms</span><span class="params">()</span> &#123;</span><br><span class="line">        System.out.println(Thread.currentThread().getName()+<span class="string">&quot;:sms&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * a:call</span></span><br><span class="line"><span class="comment"> * a:sms</span></span><br><span class="line"><span class="comment"> * b:call</span></span><br><span class="line"><span class="comment"> * b:sms</span></span><br><span class="line"><span class="comment"> */</span></span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 可重入锁 ReentrantLock</span></span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">LockDemo2</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="keyword">new</span> <span class="title class_">Thread</span>(()-&gt;&#123;</span><br><span class="line">            Phone2.call();</span><br><span class="line">        &#125;,<span class="string">&quot;a&quot;</span>).start();</span><br><span class="line">        <span class="keyword">new</span> <span class="title class_">Thread</span>(()-&gt;&#123;</span><br><span class="line">            Phone2.call();</span><br><span class="line">        &#125;,<span class="string">&quot;b&quot;</span>).start();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">class</span> <span class="title class_">Phone2</span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="type">Lock</span> <span class="variable">lock</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">ReentrantLock</span>();</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">call</span><span class="params">()</span> &#123;</span><br><span class="line">        lock.lock();</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            System.out.println(Thread.currentThread().getName()+<span class="string">&quot;:call&quot;</span>);</span><br><span class="line">            sms();</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">            lock.unlock();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">sms</span><span class="params">()</span> &#123;</span><br><span class="line">        lock.lock();</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            System.out.println(Thread.currentThread().getName()+<span class="string">&quot;:sms&quot;</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">            lock.unlock();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * a:call</span></span><br><span class="line"><span class="comment"> * a:sms</span></span><br><span class="line"><span class="comment"> * b:call</span></span><br><span class="line"><span class="comment"> * b:sms</span></span><br><span class="line"><span class="comment"> */</span></span><br></pre></td></tr></table></figure>

<blockquote>
<p>注意点: lock锁必须要lock与unlock匹配!以下情况会发生死锁</p>
</blockquote>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">call</span><span class="params">()</span> &#123;</span><br><span class="line">    <span class="comment">// 两次锁 -&gt; 一次解锁 -&gt; 死锁</span></span><br><span class="line">    lock.lock();</span><br><span class="line">    lock.lock();</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        System.out.println(Thread.currentThread().getName()+<span class="string">&quot;:call&quot;</span>);</span><br><span class="line">        sms();</span><br><span class="line">    &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">        e.printStackTrace();</span><br><span class="line">    &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">        lock.unlock();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h4 id="3-自旋锁"><a href="#3-自旋锁" class="headerlink" title="3. 自旋锁"></a>3. 自旋锁</h4><p><strong>-&gt;代码模拟</strong></p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title class_">SpinLockDemo</span> &#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title function_">main</span><span class="params">(String[] args)</span> &#123;</span><br><span class="line">        <span class="type">MySpinLock</span> <span class="variable">lock</span> <span class="operator">=</span> <span class="keyword">new</span> <span class="title class_">MySpinLock</span>();</span><br><span class="line">        <span class="keyword">new</span> <span class="title class_">Thread</span>(()-&gt;&#123;</span><br><span class="line">            lock.myLock();</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                TimeUnit.SECONDS.sleep(<span class="number">3</span>);</span><br><span class="line">            &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">            &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">                lock.myUnLock();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;).start();</span><br><span class="line">        <span class="keyword">new</span> <span class="title class_">Thread</span>(()-&gt;&#123;</span><br><span class="line">            lock.myLock();</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                TimeUnit.SECONDS.sleep(<span class="number">1</span>);</span><br><span class="line">            &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">            &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">                lock.myUnLock();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;).start();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">class</span> <span class="title class_">MySpinLock</span> &#123;</span><br><span class="line">    <span class="keyword">private</span> AtomicReference&lt;Thread&gt; reference = <span class="keyword">new</span> <span class="title class_">AtomicReference</span>&lt;&gt;();</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">myLock</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="type">Thread</span> <span class="variable">thread</span> <span class="operator">=</span> Thread.currentThread();</span><br><span class="line">        System.out.println(thread.getName()+<span class="string">&quot;准备加锁了!&quot;</span>);</span><br><span class="line">        <span class="keyword">while</span> (!reference.compareAndSet(<span class="literal">null</span>,thread));</span><br><span class="line">        <span class="comment">// 当线程未释放时,不断执行循环(自旋)</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">void</span> <span class="title function_">myUnLock</span><span class="params">()</span> &#123;</span><br><span class="line">        <span class="type">Thread</span> <span class="variable">thread</span> <span class="operator">=</span> Thread.currentThread();</span><br><span class="line">        System.out.println(thread.getName()+<span class="string">&quot;准备加锁了&quot;</span>);</span><br><span class="line">        reference.compareAndSet(thread,<span class="literal">null</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Thread-0准备加锁了</span></span><br><span class="line"><span class="comment"> * Thread-1准备加锁了</span></span><br><span class="line"><span class="comment"> * </span></span><br><span class="line"><span class="comment"> * Thread-0解锁了 </span></span><br><span class="line"><span class="comment"> * Thread-1解锁了 -&gt; 只有等Thread0解锁后,线程1才开始执行</span></span><br><span class="line"><span class="comment"> */</span></span><br></pre></td></tr></table></figure>

<h4 id="4-死锁"><a href="#4-死锁" class="headerlink" title="4. 死锁"></a>4. 死锁</h4><blockquote>
<p>形成死锁的四个条件</p>
</blockquote>
<ol>
<li><p>互斥条件：资源是独占的且排他使用，进程互斥使用资源，即任意时刻一个资源只能给一个进程使用，其他进程若申请一个资源，而该资源被另一进程占有时，则申请者等待直到资源被占有者释放。</p>
</li>
<li><p>不可剥夺条件：进程所获得的资源在未使用完毕之前，不被其他进程强行剥夺，而只能由获得该资源的进程资源释放。</p>
</li>
<li><p>请求和保持条件：进程每次申请它所需要的一部分资源，在申请新的资源的同时，继续占用已分配到的资源。</p>
</li>
<li><p>循环等待条件：在发生死锁时必然存在一个进程等待队列{P1,P2,…,Pn},其中P1等待P2占有的资源，P2等待P3占有的资源，…，Pn等待P1占有的资源，形成一个进程等待环路，环路中每一个进程所占有的资源同时被另一个申请，也就是前一个进程占有后一个进程所深情地资源。</p>
</li>
</ol>
<blockquote>
<p>死锁预防</p>
</blockquote>
<ol>
<li><p>破坏“不可剥夺”条件：一个进程不能获得所需要的全部资源时便处于等待状态，等待期间他占有的资源将被隐式的释放重新加入到 系统的资源列表中，可以被其他的进程使用，而等待的进程只有重新获得自己原有的资源以及新申请的资源才可以重新启动，执行。</p>
</li>
<li><p>破坏”请求与保持条件“：第一种方法静态分配即每个进程在开始执行时就申请他所需要的全部资源。第二种是动态分配即每个进程在申请所需要的资源时他本身不占用系统资源。</p>
</li>
<li><p>破坏“循环等待”条件：采用资源有序分配其基本思想是将系统中的所有资源顺序编号，将紧缺的，稀少的采用较大的编号，在申请资源时必须按照编号的顺序进行，一个进程只有获得较小编号的进程才能申请较大编号的进程。</p>
</li>
</ol>
<blockquote>
<p>死锁排查</p>
</blockquote>
<p><em><strong>1. 使用 <code>JPS -l</code> 定位</strong></em></p>
<p><img src= "" data-lazy-src="https://pic.unkonwn.online//20230301182858.png"></p>
<ol start="2">
<li>使用 <code>jstack 进程号</code> 获取详细信息</li>
</ol>
<p><img src= "" data-lazy-src="https://pic.unkonwn.online//20230301182816.png"></p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">Author: </span><span class="post-copyright-info"><a href="https://unkonwn.online">Ris Pika</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">Link: </span><span class="post-copyright-info"><a href="https://unkonwn.online/2023/03/01/JUC%E5%AD%A6%E4%B9%A0%E6%97%A5%E8%AE%B01/">https://unkonwn.online/2023/03/01/JUC%E5%AD%A6%E4%B9%A0%E6%97%A5%E8%AE%B01/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">Copyright Notice: </span><span class="post-copyright-info">All articles in this blog are licensed under <a target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">CC BY-NC-SA 4.0</a> unless stating additionally.</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/java/">java</a><a class="post-meta__tags" href="/tags/JUC/">JUC</a></div><div class="post_share"><div class="social-share" data-image="https://pic.unkonwn.online//wallhaven-6dl2yw.jpg?imageView/1/w/500/h/500" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://lib.baomitu.com/social-share.js/1.0.16/css/share.min.css" media="print" onload="this.media='all'"><script src="https://lib.baomitu.com/social-share.js/1.0.16/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2023/03/01/JAVA-%E4%BB%8E0%E5%88%B0helloworld/" title="JAVA 从0到helloworld"><img class="cover" src= "" data-lazy-src="https://pic.unkonwn.online//wallhaven-gpw787.jpg?imageView/1/w/500/h/500" onerror="onerror=null;src='/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">Previous Post</div><div class="prev_info">JAVA 从0到helloworld</div></div></a></div><div class="next-post pull-right"><a href="/2023/02/28/JAVA%E7%BA%BF%E7%A8%8B%E6%B1%A0%E5%AD%A6%E4%B9%A0%E6%97%A5%E8%AE%B01/" title="JAVA线程池学习日记1"><img class="cover" src= "" data-lazy-src="https://pic.unkonwn.online//wallhaven-x6ewo3.jpg?imageView/1/w/500/h/500" onerror="onerror=null;src='/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">Next Post</div><div class="next_info">JAVA线程池学习日记1</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>Related Articles</span></div><div class="relatedPosts-list"><div><a href="/2023/02/26/jwt/" title="五分钟JWT入门"><img class="cover" src= "" data-lazy-src="http://pic.unkonwn.online/wallhaven-qzr7pr.jpg?imageView/1/w/240/h/240" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-02-26</div><div class="title">五分钟JWT入门</div></div></a></div><div><a href="/2023/02/27/blocking-queue/" title="初学BlockingQueue"><img class="cover" src= "" data-lazy-src="http://pic.unkonwn.online/wallhaven-we52yp.jpg?imageView/1/w/240/h/240" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-02-27</div><div class="title">初学BlockingQueue</div></div></a></div><div><a href="/2023/02/28/JAVA%E7%BA%BF%E7%A8%8B%E6%B1%A0%E5%AD%A6%E4%B9%A0%E6%97%A5%E8%AE%B01/" title="JAVA线程池学习日记1"><img class="cover" src= "" data-lazy-src="https://pic.unkonwn.online//wallhaven-x6ewo3.jpg?imageView/1/w/500/h/500" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-02-28</div><div class="title">JAVA线程池学习日记1</div></div></a></div><div><a href="/2023/03/01/JAVA-%E4%BB%8E0%E5%88%B0helloworld/" title="JAVA 从0到helloworld"><img class="cover" src= "" data-lazy-src="https://pic.unkonwn.online//wallhaven-gpw787.jpg?imageView/1/w/500/h/500" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-03-01</div><div class="title">JAVA 从0到helloworld</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src= "" data-lazy-src="http://pic.unkonwn.online//20140802211120_t34dW.jpeg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">Ris Pika</div><div class="author-info__description"></div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">Articles</div><div class="length-num">6</div></a><a href="/tags/"><div class="headline">Tags</div><div class="length-num">13</div></a><a href="/categories/"><div class="headline">Categories</div><div class="length-num">0</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/rispika/"><i class="fab fa-github"></i><span>Follow Me</span></a></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>Announcement</span></div><div class="announcement_content">This is my Blog</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>Catalog</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E2%9D%A4%E8%AF%A5%E6%96%87%E6%A1%A3%E4%B8%BB%E8%A6%81%E8%AE%B2%E8%BF%B0%E5%8C%85%E6%8B%AC%E4%BB%A5%E4%B8%8B%E5%86%85%E5%AE%B9%E2%9D%A4"><span class="toc-number">1.</span> <span class="toc-text">❤该文档主要讲述包括以下内容❤</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#1-JMM"><span class="toc-number">2.</span> <span class="toc-text">1. JMM</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%85%B3%E4%BA%8EJMM%E7%9A%84%E4%B8%80%E4%BA%9B%E5%90%8C%E6%AD%A5%E7%9A%84%E7%BA%A6%E5%AE%9A"><span class="toc-number">2.0.1.</span> <span class="toc-text">关于JMM的一些同步的约定</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#gt-%E5%8F%98%E9%87%8F%E8%BF%90%E7%AE%97%E7%A4%BA%E4%BE%8B%E5%9B%BE"><span class="toc-number">2.0.2.</span> <span class="toc-text">-&gt; 变量运算示例图</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#2-Volatile"><span class="toc-number">3.</span> <span class="toc-text">2. Volatile</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#gt-%E4%BF%9D%E8%AF%81%E5%8F%AF%E8%A7%81%E6%80%A7"><span class="toc-number">3.1.</span> <span class="toc-text">-&gt; 保证可见性</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#1-%E9%97%AE%E9%A2%98%E4%BB%A3%E7%A0%81"><span class="toc-number">3.1.1.</span> <span class="toc-text">1.问题代码</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#2-%E9%97%AE%E9%A2%98%E8%A7%A3%E5%86%B3"><span class="toc-number">3.1.2.</span> <span class="toc-text">2.问题解决</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#gt-%E4%B8%8D%E4%BF%9D%E8%AF%81%E5%8E%9F%E5%AD%90%E6%80%A7"><span class="toc-number">3.2.</span> <span class="toc-text">-&gt; 不保证原子性</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#gt-%E9%97%AE%E9%A2%98%E4%BB%A3%E7%A0%81"><span class="toc-number">3.2.1.</span> <span class="toc-text">-&gt; 问题代码</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#gt-%E8%A7%A3%E5%86%B3%E6%96%B9%E6%A1%88"><span class="toc-number">3.2.2.</span> <span class="toc-text">-&gt; 解决方案</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#gt-%E4%BF%9D%E8%AF%81%E4%BA%86%E6%8C%87%E4%BB%A4%E4%B8%8D%E4%BC%9A%E9%87%8D%E6%8E%92"><span class="toc-number">3.3.</span> <span class="toc-text">-&gt; 保证了指令不会重排</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#gt-%E8%80%8Cvolatile%E5%8F%AF%E4%BB%A5%E9%81%BF%E5%85%8D%E6%8C%87%E4%BB%A4%E9%87%8D%E6%8E%92"><span class="toc-number">3.3.1.</span> <span class="toc-text">*** -&gt; 而volatile可以避免指令重排***</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#3-%E5%8D%95%E4%BE%8B%E6%A8%A1%E5%BC%8F"><span class="toc-number">4.</span> <span class="toc-text">3. 单例模式</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#1-%E9%A5%BF%E6%B1%891"><span class="toc-number">4.0.1.</span> <span class="toc-text">1. 饿汉1</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#2-%E9%A5%BF%E6%B1%892"><span class="toc-number">4.0.2.</span> <span class="toc-text">2. 饿汉2</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#3-%E6%87%92%E6%B1%89%E5%BC%8F-DCL"><span class="toc-number">4.0.3.</span> <span class="toc-text">3. 懒汉式 DCL</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#4-%E6%9E%9A%E4%B8%BE"><span class="toc-number">4.0.4.</span> <span class="toc-text">4. 枚举</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#4-%E6%B7%B1%E5%85%A5%E7%90%86%E8%A7%A3CAS"><span class="toc-number">5.</span> <span class="toc-text">4. 深入理解CAS</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#1-%E4%BB%80%E4%B9%88%E6%98%AFCAS"><span class="toc-number">5.0.1.</span> <span class="toc-text">1. 什么是CAS?</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#2-%E4%BB%80%E4%B9%88%E6%98%AFunsafe%E7%B1%BB"><span class="toc-number">5.0.2.</span> <span class="toc-text">2. 什么是unsafe类?</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#5-ABA%E9%97%AE%E9%A2%98"><span class="toc-number">6.</span> <span class="toc-text">5. ABA问题</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#6-%E5%8E%9F%E5%AD%90%E5%BC%95%E7%94%A8"><span class="toc-number">7.</span> <span class="toc-text">6. 原子引用</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#AtomicStampedReference%E7%B1%BB"><span class="toc-number">7.0.1.</span> <span class="toc-text">AtomicStampedReference类</span></a></li></ol></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#7-%E9%94%81"><span class="toc-number">8.</span> <span class="toc-text">7. 锁!</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#1-%E9%9D%9E%E5%85%AC%E5%B9%B3%E9%94%81%E5%92%8C%E5%85%AC%E5%B9%B3%E9%94%81"><span class="toc-number">8.0.1.</span> <span class="toc-text">1. 非公平锁和公平锁</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#2-%E5%8F%AF%E9%87%8D%E5%85%A5%E9%94%81"><span class="toc-number">8.0.2.</span> <span class="toc-text">2. 可重入锁</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#3-%E8%87%AA%E6%97%8B%E9%94%81"><span class="toc-number">8.0.3.</span> <span class="toc-text">3. 自旋锁</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#4-%E6%AD%BB%E9%94%81"><span class="toc-number">8.0.4.</span> <span class="toc-text">4. 死锁</span></a></li></ol></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>Recent Post</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/2023/03/01/JAVA-%E4%BB%8E0%E5%88%B0helloworld/" title="JAVA 从0到helloworld"><img src= "" data-lazy-src="https://pic.unkonwn.online//wallhaven-gpw787.jpg?imageView/1/w/500/h/500" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="JAVA 从0到helloworld"/></a><div class="content"><a class="title" href="/2023/03/01/JAVA-%E4%BB%8E0%E5%88%B0helloworld/" title="JAVA 从0到helloworld">JAVA 从0到helloworld</a><time datetime="2023-03-01T14:32:08.000Z" title="Created 2023-03-01 22:32:08">2023-03-01</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/03/01/JUC%E5%AD%A6%E4%B9%A0%E6%97%A5%E8%AE%B01/" title="JUC学习日记1"><img src= "" data-lazy-src="https://pic.unkonwn.online//wallhaven-6dl2yw.jpg?imageView/1/w/500/h/500" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="JUC学习日记1"/></a><div class="content"><a class="title" href="/2023/03/01/JUC%E5%AD%A6%E4%B9%A0%E6%97%A5%E8%AE%B01/" title="JUC学习日记1">JUC学习日记1</a><time datetime="2023-03-01T12:52:40.000Z" title="Created 2023-03-01 20:52:40">2023-03-01</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/02/28/JAVA%E7%BA%BF%E7%A8%8B%E6%B1%A0%E5%AD%A6%E4%B9%A0%E6%97%A5%E8%AE%B01/" title="JAVA线程池学习日记1"><img src= "" data-lazy-src="https://pic.unkonwn.online//wallhaven-x6ewo3.jpg?imageView/1/w/500/h/500" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="JAVA线程池学习日记1"/></a><div class="content"><a class="title" href="/2023/02/28/JAVA%E7%BA%BF%E7%A8%8B%E6%B1%A0%E5%AD%A6%E4%B9%A0%E6%97%A5%E8%AE%B01/" title="JAVA线程池学习日记1">JAVA线程池学习日记1</a><time datetime="2023-02-28T10:02:52.000Z" title="Created 2023-02-28 18:02:52">2023-02-28</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/02/27/blocking-queue/" title="初学BlockingQueue"><img src= "" data-lazy-src="http://pic.unkonwn.online/wallhaven-we52yp.jpg?imageView/1/w/240/h/240" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="初学BlockingQueue"/></a><div class="content"><a class="title" href="/2023/02/27/blocking-queue/" title="初学BlockingQueue">初学BlockingQueue</a><time datetime="2023-02-27T07:50:33.000Z" title="Created 2023-02-27 15:50:33">2023-02-27</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/2023/02/26/jwt/" title="五分钟JWT入门"><img src= "" data-lazy-src="http://pic.unkonwn.online/wallhaven-qzr7pr.jpg?imageView/1/w/240/h/240" onerror="this.onerror=null;this.src='/img/404.jpg'" alt="五分钟JWT入门"/></a><div class="content"><a class="title" href="/2023/02/26/jwt/" title="五分钟JWT入门">五分钟JWT入门</a><time datetime="2023-02-26T13:39:36.000Z" title="Created 2023-02-26 21:39:36">2023-02-26</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2023 By Ris Pika</div><div class="framework-info"><span>Framework </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>Theme </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text">unknown!</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="Read Mode"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="Switch Between Light And Dark Mode"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="Toggle between single-column and double-column"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="Setting"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="Table Of Contents"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="Back To Top"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.min.js"></script><script src="https://lf3-cdn-tos.bytecdntp.com/cdn/expire-1-M/vanilla-lazyload/17.3.1/lazyload.iife.min.js"></script><script src="https://lf6-cdn-tos.bytecdntp.com/cdn/expire-1-M/node-snackbar/0.1.16/snackbar.min.js"></script><div class="js-pjax"></div><script defer src="/live2d-widget/autoload.js"></script><canvas class="fireworks" mobile="true"></canvas><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/fireworks.min.js"></script><script defer="defer" id="fluttering_ribbon" mobile="true" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/canvas-fluttering-ribbon.min.js"></script><script id="canvas_nest" defer="defer" color="0,0,255" opacity="0.7" zIndex="-1" count="99" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/canvas-nest.min.js"></script><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/activate-power-mode.min.js"></script><script>POWERMODE.colorful = true;
POWERMODE.shake = false;
POWERMODE.mobile = false;
document.body.addEventListener('input', POWERMODE);
</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">Search</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  Loading the Database</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="Search for Posts" type="text"/></div></div><hr/><div id="local-search-results"></div></div></div><div id="search-mask"></div><script src="/js/search/local-search.js"></script></div></body></html>